package pers.amos.eshop.advance.price.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pers.amos.eshop.advance.price.mapper.ProductPriceMapper;
import pers.amos.eshop.advance.price.model.ProductPrice;
import pers.amos.eshop.advance.price.redis.RedisUtils;
import pers.amos.eshop.advance.price.service.ProductPriceService;


@Service
public class ProductPriceServiceImpl implements ProductPriceService {

    @Autowired
    private ProductPriceMapper productPriceMapper;

    @Autowired
    private RedisUtils redisUtils;

    private final static String PRODUCT_PRICE_KEY_PREFIX = "product_price_";

    @Override
    public void add(ProductPrice productPrice) {
        productPriceMapper.add(productPrice);

        redisUtils.set(PRODUCT_PRICE_KEY_PREFIX + productPrice.getId(), productPrice.toString());
    }

    @Override
    public void update(ProductPrice productPrice) {
        productPriceMapper.update(productPrice);

        redisUtils.set(PRODUCT_PRICE_KEY_PREFIX + productPrice.getId(), productPrice.toString());
    }

    @Override
    public void delete(Long id) {
        productPriceMapper.delete(id);

        redisUtils.delete(PRODUCT_PRICE_KEY_PREFIX + id);
    }

    @Override
    public ProductPrice findById(Long id) {
        return productPriceMapper.findById(id);
    }

    @Override
    public ProductPrice findByProductId(Long productId) {
        String productPrice = redisUtils.get(PRODUCT_PRICE_KEY_PREFIX + productId);
        if (StrUtil.isNotBlank(productPrice)) {
            return JSONUtil.toBean(productPrice, ProductPrice.class);
        }

        return productPriceMapper.findByProductId(productId);
    }

}
